package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.domain.dto.PayOrderDTO;
import com.hmall.trade.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**超时订单监听器*/
@Component
public class OrderDelayMessageListener {
    @Resource
    private IOrderService orderService;
    @Resource
    private PayClient payClient;

    /**
     *
     * */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name= MqConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name=MqConstants.DELAY_EXCHANGE_NAME,delayed = "true"),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelayMessage(Long orderId){
        //1.查询订单
        Order order = orderService.getById(orderId);
        //2.检测订单状态，判断是否已支付
        if(null == order || order.getStatus()!=1){
            //查不到订单 或者 订单状态不是未付款（被其他地方处理了）则返回
            return;
        }
        //3.订单状态未付款，查询一下支付流水状态
        PayOrderDTO payDTO = payClient.queryPayOrderByBizOrderNo(orderId);
        //4.判断支付单是否支付
        if(null != payDTO && payDTO.getStatus()==3){
            //支付单支付成功，则更新交易模块订单为已支付
            orderService.markOrderPaySuccess(orderId);
        }else {
            orderService.cancelOrder(orderId);

        }
    }
}
